package it.infodea.tapestrydea.components.mail;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.tapestry5.ComponentEventCallback;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.IncludeStylesheet;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.internal.util.Holder;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.slf4j.Logger;

@IncludeJavaScriptLibrary("../AjaxFileUpload.js")
@IncludeStylesheet("AjaxMultipleFileUpload.css")
public class AjaxMultipleFileUpload {

	public static final String UPLOAD_EVENT_NAME = "uploadedItem";

	@Parameter
	private String onCompleteCallback;

	
	@SuppressWarnings("unused")
	@Property private String uploadFormDivId;
	
	private UploadedFile uploadedFile;

	@Component
	private Form uploadForm;
	
	@Inject
	private Logger logger;
	
	@Inject
	private ComponentResources resources;
	
	@Inject
	private RenderSupport support;
	
	@SetupRender
	void setup(){
		uploadFormDivId = resources.getId() + "ContainerDiv";
	}

	@AfterRender
	void afterRender(){
		String options = "{}";
		if(resources.isBound("onCompleteCallback") && onCompleteCallback != null){
			options = "{onComplete:" + onCompleteCallback + "}";
		}
		support.addScript("$('%1$s').observe('submit', function(evt){" +
				"new AjaxFileUpload().submit($('%1$s'), %2$s);});", uploadForm.getClientId(), options);
		
	}
	
	void onSuccess() {
		if(uploadedFile != null){
			triggerEvent(UPLOAD_EVENT_NAME, uploadedFile);
		}
		
	}
	
	void onUploadException(FileUploadException ex){
		logger.error(ex.getMessage());
		uploadForm.recordError(ex.getMessage());
    }
	
	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}
	
	private Object triggerEvent(String eventName, Object ...params){

		final Holder<Object> holder = Holder.create();
		
		ComponentEventCallback<Object> handler = new ComponentEventCallback<Object>() {

			public boolean handleResult(Object result) {
				holder.put(result);
				return true;
			}
		};

		resources.triggerEvent(eventName, params, handler);
		
		return holder.get();
	}

}
